package www.nupter.org.njuptask.http;


import android.util.Log;
import android.widget.ImageView;

import com.alibaba.fastjson.JSON;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import www.nupter.org.njuptask.application.MyApplication;
import www.nupter.org.njuptask.model.BaseInfo;


/**
 * Created by fangzhenyi on 15/11/10.
 */
public class HttpRequestUtil {
    public static final String ERROR_STATUS = "error";
    public static final String SUCESS_STATUS = "success";

    public static <T> void getMethod(RequestParams requestParams, final Class<T> bean, final HttpCallBack<T> httpCallBack) {
        x.http().get(requestParams, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Log.i("数据：",result);
                BaseInfo baseInfo=JSON.parseObject(result,BaseInfo.class);
                if (baseInfo.getStatus().equals("success")){
                    T t=JSON.parseObject(result,bean);
                    httpCallBack.success(t);
                }else {
                    httpCallBack.erro(baseInfo.getData());
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                System.out.println(ex.toString());
                httpCallBack.erro("网络错误");
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    public static <T> void postMethod(RequestParams requestParams, final Class<T> bean, final HttpCallBack<T> httpCallBack) {
        x.http().post(requestParams, new Callback.CommonCallback<String>() {
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                System.out.println(ex.toString());
                httpCallBack.erro("网络错误");
            }
            @Override
            public void onSuccess(String result) {
                Log.i("数据：",result);
                BaseInfo baseInfo=JSON.parseObject(result,BaseInfo.class);
                if (baseInfo.getStatus().equals("success")){
                    T t=JSON.parseObject(result,bean);
                    httpCallBack.success(t);
                }else {
                    httpCallBack.erro(baseInfo.getData());
                }
            }

            @Override
            public void onCancelled(CancelledException cex) {
            }

            @Override
            public void onFinished() {
            }
        });
    }
    public static void initImage(ImageView imageView, String imageUrl) {
        MyApplication.initImage(imageView,imageUrl);
    }

    public static void initLocalImage(ImageView imageView, String path) {
        MyApplication.initLocalImage(imageView, path);
    }
}
